<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="药品名称" prop="drugName">
        <el-select
          v-model="queryParams.drugName"
          placeholder="请选择药品名称"
          clearable
          filterable
          @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in drugList"
            :key="item.drugId"
            :label="item.drugName"
            :value="item.drugName">
          </el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="总金额" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入总金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['patient_drug:patient_drug:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['patient_drug:patient_drug:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['patient_drug:patient_drug:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['patient_drug:patient_drug:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="patient_drugList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="药单序号" align="center" prop="takeId" />
      <el-table-column label="患者姓名" align="center" prop="patientName" />
      <el-table-column label="药房名称" align="center" prop="pharmacyName" />
<!--      <el-table-column label="药品ID" align="center" prop="drugId" />-->
      <el-table-column label="药品名称" align="center" prop="drugName" />
      <el-table-column label="取药数量" align="center" prop="quantity" />
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="时间" align="center" prop="takeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.takeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['patient_drug:patient_drug:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['patient_drug:patient_drug:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名" style="width: 200px;" />
        </el-form-item>

        <el-form-item label="药房ID" prop="pharmacyId">
          <el-select v-model="form.pharmacyId" placeholder="请选择药房ID" clearable filterable >
            <el-option
              v-for="item in pharmacyList"
              :key="item.pharmacyId"
              :label="item.pharmacyName"
              :value="item.pharmacyId">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 药品名称选择（联动药品ID） -->
        <el-form-item label="药品名称" prop="drugName">
          <el-select
            v-model="form.drugName"
            placeholder="请选择药品名称"
            clearable
            @change="handleDrugNameChange">
            <el-option
              v-for="item in drugList"
              :key="item.drugId"
              :label="item.drugName"
              :value="item.drugName">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 药品ID（自动填充，只读） -->
        <el-form-item label="药品ID" prop="drugId" >
          <el-input
            v-model="form.drugId"
            placeholder="选择药品名称后自动生成"
            readonly
            disabled
            style="width: 200px;">
          </el-input>
        </el-form-item>

        <el-form-item label="取药数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入取药数量" style="width: 200px;" />
         当前库存<el-input  style="width: 100px;" />
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<!--整合时只需要修改路径-->
<script>
import { listPatient_drug, getPatient_drug, delPatient_drug, addPatient_drug, updatePatient_drug } from "@/api/patient_drug/patient_drug"
import { listManagement } from "@/api/BasicSettings/management" // 假设有这个API
import drugAndPharmacy from "@/api/pharmacy/mixins/drugAndPharmacy.js"

export default {
  name: "Patient_drug",
  mixins: [drugAndPharmacy],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 病人取药表格数据
      patient_drugList: [],
      // 药品列表数据（用于下拉选择）
      drugList: [],
      // 药房列表数据（用于下拉选择）
      pharmacyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        patientName: null,
        drugName: null,
        totalAmount: null,
      },
      // 表单参数
      form: {
        takeId: null,
        patientName: null,
        pharmacyId: null,
        drugId: null,
        drugName: null,
        quantity: null,
        totalAmount: null,
        takeTime: null,
        remark: null
      },
      // 表单校验规则
      rules: {
        patientName: [
          { required: true, message: "患者姓名不能为空", trigger: "blur" }
        ],
        pharmacyId: [
          { required: true, message: "药房ID不能为空", trigger: "blur" }
        ],
        drugName: [
          { required: true, message: "药品名称不能为空", trigger: ["blur", "change"] }
        ],
        drugId: [
          { required: true, message: "药品ID不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "取药数量不能为空", trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "总金额不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getDrugList()
    this.getPharmacyList()
  },
  methods: {
    /** 查询病人取药列表 */
    getList() {
      this.loading = true
      listPatient_drug(this.queryParams).then(response => {
        this.patient_drugList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 获取药品列表数据 */
    getDrugList(){
      getDrugNameList(this.queryParams).then(response => {
        this.drugList = response.rows
        console.log("药品列表数据：", this.drugList)
      }).catch(error => {
        console.error("获取药品列表失败：", error)
      })
    },

    /** 获取药房列表数据 */
    getPharmacyList(){
      getPharmacyNameList(this.queryParams).then(response => {
        this.pharmacyList = response.rows
        console.log("药房列表数据：", this.pharmacyList)
      }).catch(error => {
        console.error("获取药房列表失败：", error)
      })
    },

    /** 选择药品名称后自动填充药品ID */
    handleDrugNameChange(selectedDrugName) {
      // 清空选择时同步清空ID
      if (!selectedDrugName) {
        this.form.drugId = null
        return
      }

      // 根据选择的药品名称匹配对应的ID
      const matchedDrug = this.drugList.find(item => item.drugName === selectedDrugName)
      if (matchedDrug) {
        this.form.drugId = matchedDrug.drugId
      } else {
        this.form.drugId = null
        this.$message.warning("未找到对应的药品信息")
      }
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        takeId: null,
        patientName: null,
        pharmacyId: null,
        drugId: null,
        drugName: null,
        quantity: null,
        totalAmount: null,
        takeTime: null,
        remark: null
      }
      this.resetForm("form")
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.takeId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加病人取药"
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const takeId = row.takeId || this.ids
      getPatient_drug(takeId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改病人取药"
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.takeId != null) {
            updatePatient_drug(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPatient_drug(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const takeIds = row.takeId || this.ids
      this.$modal.confirm(`是否确认删除病人取药编号为"${takeIds}"的数据项？`).then(() => {
        return delPatient_drug(takeIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('patient_drug/patient_drug/export', {
        ...this.queryParams
      }, `patient_drug_${new Date().getTime()}.xlsx`)
    },
  }
}
</script>
